const app = getApp();
const { module, appJson, tabbar_type } = app.siteInfo;
const _util = require('./util.js');
const WxNotificationCenter = require('../../utils/WxNotificationCenter/WxNotificationCenter.js');
const { getUserInfo } = require('../../../common/utils/ws/wsxcx-opendata-sdk');

Page({
  _privateData: {
    days: '',
    isUnloaded: false,
  },
  data: {
    existCard: {},
    cardList: [],
    showCardList: false,
    loadingCardList: false,
    defaultAvatar: './img/default-avatar.png',
    liked: false,
    self: false,
    toggleMore: true,
    appJson: appJson,
    module: module,
    audioStatusLabel: '就绪',
    isWXWork: app.isWXWork,
    isShowLast: false,
    lastCardsList:[],
    isMySelf: true,
    popContent:'点击“添加到我的小程序”，微信下拉快速打开',
    showPopover:false,
    showWelcome: false,
    showSubscription:false,
    showSubscription2: false,
    firstConsult: true,
    disable: false,
    isShowBadge: false,
    labelAlias: {},
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    showExtra: module !== 'ws_training_education' && module.indexOf('ws_micro_shop') === -1,
    userInfo: wx.getStorageSync('user_info') || {},
    isGetUserInfo: false,
    isGetMobile: false,
    getUserInfoFn:'',
    getUserMobileFn:'',
    cancelAuthMobileFn:'',
    showGetUserInfo: false,
    showBindMobile: false,
    isRefresh: true,
  },

  // 根据不同模块，处理登录和数据请求。
  onLoad: function (options) {
    // if (options.cardid && options.openid) { 
    //   wx.setStorageSync('shareCard', options);
    // } else if (options.scene){
    //   wx.setStorageSync('scene', options);
    // };
    // let shareCard = wx.getStorageSync('shareCard') || '';
    // let scene = wx.getStorageSync('scene') || '';
    // if (shareCard.openid && shareCard.cardid) {
    //   this.options = shareCard;
    // } else if (scene) {
    //   this.options = scene;
    // }
    console.log("======options=======", options)
    // let showHomeBtn = _util.shouldShowFixedMenu('common/component/universal-card/card-show');
    // showHomeBtn && this.findActualHome();
    // showHomeBtn && this.setData({
    //   'floatItems[0].show': true,
    // });
    // 如果多个页面埋点，需要加页面命名空间。
    app.v8_card_action_log = [];
    this.getLiveScreen();
    this.initInnerAudioContext();
    this.getLabelAlias();
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid') || wx.getStorageSync('userInfo').openid;
    this.getLastCards(openid);
    this.checkUserTelephone(openid);
    this.checkAuth();
  },

  onShow: function(){
    if (this.data.isRefresh){
    this.initCard();
    }
    setTimeout(() => {
      this.setData({ isRefresh: true });
    },1000)
    // let user_info = wx.getStorageSync('user_info');
    // this.setData({
    //   isGetUserInfo:(user_info.nickname || user_info.nickName) ? true : false,
    //   isGetMobile: (user_info.mobile) ? true: false
    // })
  },

  onHide: function() {
    this.reportAction();
    this.__innerAudioContext && this.__innerAudioContext.src && this.audioStop();
    this.options = {};
  },

  onUnload: function() {
    this.reportAction();
    this.__innerAudioContext && this.__innerAudioContext.src && this.audioStop();
    this.__innerAudioContext && this.__innerAudioContext.destroy();
    this._privateData.isUnloaded = true;
    this.options = {};
  },

  // 加载名片
  initCard: function() {
    let that = this;
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid') || wx.getStorageSync('userInfo').openid; // 从缓存中获取的本人的openID
    let parsedOptions = this.parseOptions(this.options);
    if (!parsedOptions) {
      this.getLastCard(openid);
    } else {
      if (parsedOptions.sid) {
        app.ws_micro_shop_globalData.shopid = parsedOptions.sid;
      }
      let to_openid = parsedOptions.openidNew; // === this.data.fromOpenid === opts.openid 名片主人的openID
      let id = parsedOptions.cardid || parsedOptions.c; // 名片cardID
      let share_scene = parsedOptions.share_scene || parsedOptions.s || '';
      let shareSetting = wx.getStorageSync('share_setting');

      this.setData({ share_scene, id, fromOpenid: to_openid || '' });

      // 老用户本地有登录信息 && 从名片分享等途径过来的
      if (openid && id && to_openid) {
        if (openid === to_openid) return this.goToPreview();
        this.setData({ openid, self: openid === to_openid, share_scene, id, fromOpenid: to_openid });
        this.cardInfoInit(openid, id, to_openid);
        this.bindInfo(openid, to_openid, share_scene, shareSetting);
        wx.setStorageSync('openid', openid);
      }

      // 新用户或者本地无信息 && 从名片分享过来的；可能会重复登录，因为app onlaunch里也会去登录
      if (!openid && to_openid) {
        if (module === 'ws_micro_shop') {
          app.ws_micro_shoplogin().then(function() {
            openid = wx.getStorageSync('OPENID');
            that.setData({ openid, self: openid === to_openid, share_scene, id, fromOpenid: to_openid });
            wx.setStorageSync('openid', openid);
            if (openid === to_openid) return that.goToPreview();
            that.cardInfoInit(openid, id, to_openid);
            that.bindInfo(openid, to_openid, share_scene, shareSetting);
          });
        } else {
          WxNotificationCenter.addNotification('hasLogined', that.getNotificationAppLogin, that);
        }
      }

      // 从分销海报等途径过来的
      if (parsedOptions.from_uid || parsedOptions.u) {
        let uid = parsedOptions.from_uid || parsedOptions.u;
        !openid && WxNotificationCenter.addNotification('hasLogined', that.getNotificationAppLogin, that);
        openid && this.setData({ openid });
        openid && WxNotificationCenter.addNotification('gotTargetOpenID', that.getNotificationAfterGetTargetOpenID, that);

        app.util.request({
          url: 'card/api/get_fans',
          data: { uid },
          success: function (res) {
            if (Number(res.data.errno) === 0) {
              to_openid = res.data.data.openid;
              console.log('line after get_fans: ', id, to_openid);
              that.setData({ fromOpenid: to_openid });
              if (module === 'ws_micro_shop') {
                that.bindInfo(openid, to_openid, share_scene, shareSetting);
                
                if (!openid) {
                  app.ws_micro_shoplogin().then(function() {
                    openid = wx.getStorageSync('OPENID');
                    if (openid === to_openid) return that.goToPreview();
                    that.setData({ openid, self: openid === to_openid });
                    that.cardInfoInit(openid, id, to_openid, uid);
                  });
                } else {
                  if (openid === to_openid) return that.goToPreview();
                  that.setData({ openid, self: openid === to_openid });
                  that.cardInfoInit(openid, id, to_openid, uid);
                }
              } else {
                WxNotificationCenter.postNotificationName('gotTargetOpenID', to_openid);
              }
            }
          },
        });
      }
    }
  },

  // 获取标签别名
  getLabelAlias() {
    app.util.request({
      url: 'card/api/aliasList',
      success: res => {
        if (res.data && res.data.errno === 0) {
          const data = res.data.data;
          this.setData({ labelAlias: data });
        }
      },
    });
  },

  // 播放音频
  initInnerAudioContext() {
    this.__innerAudioContext = wx.createInnerAudioContext();
    this.__innerAudioContext.onError((err) => {
      console.log('__innerAudioContext error: ', err);
    });
  },

  previewPicture(e) {
    let { url, urls } = e.currentTarget.dataset;
    wx.previewImage({
      current: url,
      urls,
    });
  },



  getNotificationAppLogin: function (openID) {
    let cardID = this.data.id;
    let targetOpenID = this.data.fromOpenid;
    let share_scene = this.data.share_scene;
    let shareSetting = wx.getStorageSync('share_setting');

    wx.setStorageSync('openid', openID);
    if (!targetOpenID) return WxNotificationCenter.addNotification('gotTargetOpenID', this.getNotificationAfterGetTargetOpenID, this);

    this.setData({ openid: openID, self: openID === targetOpenID });
    if (openID === targetOpenID) return this.goToPreview();
    this.cardInfoInit(openID, cardID, targetOpenID);
    this.bindInfo(openID, targetOpenID, share_scene, shareSetting);
  },

  getNotificationAfterGetTargetOpenID: function (targetOpenID) {
    let cardID = this.data.id;
    let openID = this.data.openid;
    let share_scene = this.data.share_scene;
    let shareSetting = wx.getStorageSync('share_setting');

    this.setData({ self: openID === targetOpenID });
    if (openID === targetOpenID) return this.goToPreview();
    this.cardInfoInit(openID, cardID, targetOpenID);
    this.bindInfo(openID, targetOpenID, share_scene, shareSetting);
  },

  cardInfoInit: function (openID, cardID, targetOpenID, uid) {
    // 包括绑定上下级；检查是否点赞；获取卡片信息；
    this.checkLikeInfo(openID, cardID);
    this.bindFrom(openID, targetOpenID, uid || '').then(() => {
      this.getCardInfo(openID, cardID, targetOpenID);
    });
  },

  bindInfo: function (openID, targetOpenID, shareScene, shareSetting) {
    module === 'ws_micro_shop' && app.getStoreData().then(() => {
      this.bindParent(targetOpenID, shareSetting);
    });
    module === 'ws_diancan_multi' && app.util.request({
      url: 'entry/wxapp/Binding',
      cachetime: '0',
      data: { fx_user: openID, user_id: targetOpenID, share_scene: shareScene },
      success(res) { console.log('分销绑定上下级成功！') },
      fail(res) { console.log('分销绑定上下级失败！') },
    });
  },

  checkIsMy: function(openid, toOpen) {
    // TODO
  },

  bindFrom(openid, fromOpenid, uid) {
    return new Promise((resolve, reject) => {
      const { share_scene } = this.data;
      app.util.request({
        url: 'card/api/bind_from',
        data: {
          openid,
          from_openid: fromOpenid,
          from_uid: uid,
          share_scene,
        },
        complete: () => {
          resolve();
        },
      });
    });
  },

  onShareAppMessage: function (res) {
    const { name, id: cardid, openid, share_title } = this.data.existCard;

    this.setData({
      shareModalVisible: false,
      isRefresh: false 
    });

    this.collectAction('shareCard', true);
    return {
      title: share_title || '你好，我是' + name + '，这是我的名片，请惠存',
      path: '/common/component/universal-card/card-show?openidNew=' + openid + '&cardid=' + cardid + '&share_scene=3',
    };
  },

  // 请求名片数据
  getCardInfo(openid, id, to_openid) {
    console.log('openid:', openid);
    console.log('id:', id);
    console.log('to_openid:', to_openid);
    let that = this;
    app.util.request({
      url: 'card/api/red_card',
      data: { openid, id },
      success: res => {
        if (Number(res.data.errno) === 0) {
          //that.checkAuth();
          const existCard = res.data.data;
          existCard.images = (existCard.images || []).filter(v => v);
          that.setData({
            existCard,
            isMySelf: (openid == to_openid)? true: false,
            fromOpenid: existCard.openid
          }, () => {
            that.audioContext();
            that.createAnimation(existCard.audioDuration);
            that.getCardRecommentGoodsList(existCard.openid);
          });
          wx.setStorageSync('masterInfo', existCard);  // 留言页面用到
          // 获取针对该用户的访客信息
          app.util.request({
            url: 'card/api/get_member_record',
            data: {
              openid: to_openid,
              op: '1',
              page: '1',
              pagesize: '10',
              cardid: existCard.id || id,
            },
            success: res => {
              if (Number(res.data.errno) === 0) {
                const guests = res.data.data.list;
                const guestsCount = Number(res.data.data.total);
                that.setData({
                  guests: guests.slice(0, 5),
                  guestsCount,
                });
              }
            },
          });
        }
        if (_util.first_visit) {
          that.setData({
            showPopover: true,
            showMyPopover: true,
          })
          setTimeout(() => {
            that.setData({
              showMyPopover: false,
            })
          }, 3000)

          setTimeout(() => {
            that.setData({
              showPopover: false,
              showWelcome: true,
            })
            _util.first_visit = false;
          }, 10000)
        }
      },
    });
  },

  // 是否点赞过
  checkLikeInfo(openid, id) {
    let that = this;
    app.util.request({
      url: 'card/api/get_record',
      data: {
        openid,
        cardid: id,
      },
      success: function (res) {
        if (Number(res.data.errno) === 0) {
          if (Number(res.data.data.like) === 1) {
            that.setData({ liked: true});
          } else {
            that.setData({ liked: false });
          }
        }
      },
    });
  },

  likeHandler(e) {
    const that = this;
    let { openid, existCard, liked } = this.data;
    this.setData({disable: true})
    app.util.request({
      url: 'card/api/add_record',
      data: {
        openid,
        op: '2',
        cardid: existCard.id,
      },
      success: function (res) {
        that.setData({ disable: false })
        if (Number(res.data.errno) === 0) {
          if (Number(res.data.data.flag) === 1) {
            existCard.like = Number(existCard.like) + 1;
            liked = true;
            wx.showToast({
              title: '已赞',
            });
            that.collectAction('likeAdd', true);
          } else {
            existCard.like = Number(existCard.like) - 1;
            liked = false;
            wx.showToast({
              title: '取消点赞',
            });
            that.collectAction('likeReduce', true);
          }

          that.setData({ existCard, liked });
        } else {
          wx.showToast({
            title: '操作失败',
            icon: 'none',
          });
        }
      },
    });
  },

  addToBook(e) {
    const { name, mobile, address, email, company, wechatId, position } = this.data.existCard;
    wx.addPhoneContact({
      firstName: name,
      mobilePhoneNumber: mobile,
      addressStreet: address,
      organization: company,
      title: position,
      weChatNumber: wechatId,
      email: email,
    });
    this.collectAction('addToBook', true);
    this.setData({isRefresh: false});
  },

  gotoHome(e) {
    this.collectAction('gotoHome', true);
    const homeModule = appJson[0];
    let moduleName = homeModule.module;
    let tpl = app.siteInfo.template_num;
    let url = '';
    if (moduleName === 'ws_micro_company' && tpl) {
      url = moduleName + (tpl === '0' ? '_visual' : '_' + tpl) + '/pages/index/index';
    } else {
      if (homeModule.homePage) {
        url = homeModule.homePage;
      } else if (Number(tabbar_type) === 2 && homeModule.tabBar.v_list) {
        url = homeModule.tabBar.v_list[0].pagePath;
      } else {
        url = homeModule.tabBar.list[0].pagePath;
      }
    }
    app.util.navigateTo(url);
  },

  findActualHome() {
    const homeModule = appJson[0];
    let actualTab;
    if (Number(tabbar_type) === 2 && homeModule.tabBar.v_list) {
      actualTab = homeModule.tabBar.v_list.find(item => item.pagePath === homeModule.homePage) || homeModule.tabBar.v_list[0];
    } else {
      actualTab = homeModule.tabBar.list.find(item => item.pagePath === homeModule.homePage) || homeModule.tabBar.list[0];
    }
    this.setData({ actualTab: actualTab });
  },

  goToPreview(e) {
    let that = this;
    // not real gotoPreview
    // app.util.navigateTo('/common/component/universal-card/card-preview', {}, true);

    // 3.1 有名片信息，显示本人名片信息
    // 3.2 没有名片，显示创建名片按钮。 进入编辑页，编辑的回退、跳转逻辑得注意。
    // 注：card-preview页面还需要留着，因为要留本人名片入口页面，不然如果有options，本页也当做本人名片信息来处理，则永远进不到自己名片

    // 以下部分逻辑来自 card-preview页面，后续走自己逻辑
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');

    this.setData({
      isMySelf: true,
      isEmptyCard: false,
    });

    if (!openid) {
      // 需要登录
      if (module === 'ws_micro_shop') {
        app.ws_micro_shoplogin().then(function () {
          openid = wx.getStorageSync('OPENID');
          that.setData({ openid });
          that.getCardDetail(openid);
        });
      } else {
        app.util._wxLogin().then(res => {
          openid = res.openid || res.data.data.openid;
          that.setData({ openid });
          that.getCardDetail(openid);
        });
      }
    } else {
      this.setData({ openid });
      this.getCardDetail(openid);
    }
  },

  // 前往留言列表
  gotoMsgList() {
    let openid = this.data.openid;
    let id = this.data.existCard.id;
    let url = 'common/component/universal-card/pages/msg-list?openid=' + openid + '&cardid=' + id;
    app.util.navigateTo(url);
  },

  gotoMsg() {
    let { id, openid, fromOpenid, to_openid, existCard, guestMobile} = this.data;
    this.setData({ isRefresh: false });
    this.collectAction('gotoMsg', true);
    if (!guestMobile) {
      _util.checkUserTelephone.call(this);
    } else {
      app.util.request({
        url:'card/api/checkVistorFirstChart',
        data:{
          openid: existCard.openid || to_openid,
          cardid: existCard.id || id,
        },
        success: res => {
          if(res.data.errno == 0){
            wx.setStorageSync('vistorFirstChart',1);
          } else {
            wx.setStorageSync('vistorFirstChart',0);
          }
          this.collectAction('gotoMsg', true);
          let url = '/common/component/universal-card/pages/message?openid=' + openid + '&cardid=' + (id || existCard.id) + '&m_id=0&scene=inner&to_openid=' + (fromOpenid || existCard.openid);
          url += '&guestMobile=' + guestMobile;
          console.log("=======gotoMsg=====", url)
          app.util.navigateTo(url);
        }
      })
    }
  },

  doCall(e) {
    const mobile = e.currentTarget.dataset.mobile;
    const exp = app.util.phoneExp.mobile;
    if (mobile && exp.test(mobile)) {
      wx.makePhoneCall({
        phoneNumber: mobile,
        success: () => {
          this.collectAction('doCall', true);
        },
        fail: () => {
          this.collectAction('doCall', false);
        },
      });
    } else if (mobile && !exp.test(mobile)) {
      wx.showToast({
        title: '无效的号码',
        icon: 'none',
      });
      this.collectAction('doCall', false);
    }
  },

  checkLocation(e) {
    const { latitude, longitude, address } = this.data.existCard;
    wx.openLocation({
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      success: () => {
        this.collectAction('checkLocation', true);
      },
      fail: () => {
        address && wx.setClipboardData({
          data: address,
          success: () => {
            wx.showToast({
              title: '地址已经复制',
              icon:'none'
            })
            this.collectAction('addAddress', true);
          },
          fail: () => {
            this.collectAction('addAddress', false);
          },
        });
      },
    });
  },

  // 商城绑定分销上级方法
  bindParent: function (openid, share_setting) {
    if (share_setting.level > 0) {
      app.ws_micro_shoprequest({
        url: app.api.share.bind_parent,
        data: { parent_id: openid },
        success: function (res) {
          if (Number(res.code) === 0) {
            console.log('bind parent success.');
          } else {
            console.error(res);
          }
        },
        fail: function (err) {
          console.log(err);
        },
      });
    }
  },

  // 页面级别的分享者信息收集。
  parseOptions(options) {
    let optionsKeys = Object.keys(options);
    let scene = options && options.scene;
    if (optionsKeys.length === 0) {
      return false;
    } else if (optionsKeys.length === 1 && optionsKeys.indexOf('scene') === 0) {
      let scenePair = scene && decodeURIComponent(scene).split('&');
      let sceneObj = {};
      scenePair.forEach(function (item) {
        let key = item.slice(0, item.indexOf('='));
        let value = item.slice(item.indexOf('=') + 1, item.length);
        sceneObj[key] = value;
      });
      return sceneObj;
    } else {
      return options;
    }
  },

  showActions(e) {
    return this.setData({
      shareModalVisible: true,
      actionSheetType: 'card',
    });
  },

  shareModalClose(e) {
    this.setData({
      shareModalVisible: false,
    });
  },

  // 生成海报？
  createThumb(e) {
    let card_id = this.data.existCard.id;
    let openid = this.data.fromOpenid;
    let url = '/common/component/universal-card/pages/msg-list?openid=' + openid + '&cardid=' + card_id + '&isCard=1';
    app.util.navigateTo(url);
    this.collectAction('createThumb', true);
    return this.setData({
      shareModalVisible: false,
    });
  },

  toggleMore(e) {
    this.setData({
      toggleMore: !this.data.toggleMore,
    });
    this.collectAction('toggleMore', true);
  },

  collectAction(name, result = true) {
    let logs = app.v8_card_action_log;
    (!logs || !Array.isArray(logs)) && (app.v8_card_action_log = []);
    app.v8_card_action_log.push({ name, result, timestamp: Math.floor(Date.now() / 1000) });
  },

  reportAction() {
    let data = app.v8_card_action_log;
    let { existCard = '' } = this.data;
    data instanceof Array && data.length > 0 && app.util.statRequest({
      pt: getCurrentPages().pop().route,
      pm: JSON.stringify(getCurrentPages().pop().options),
      tm: 0,
      cn: 'click',
      tp: 2,
      aa: JSON.stringify(data),
      card_id: existCard && existCard.id,
    });
    app.v8_card_action_log = [];
  },

  createAnimation(time) {
    const animationBar = wx.createAnimation({
      duration: time || 1000,
      timingFunction: 'linear',
    });
    const animationBlock = wx.createAnimation({
      duration: time || 1000,
      timingFunction: 'linear',
    });
    this.__animationBlock = animationBlock;
    this.__animationBar = animationBar;
  },

  animationAudioplayBar(status) {
    status === 'playing' && this.__animationBar.width(this.data.x).step();
    status === 'stop' && this.__animationBar.width(0).step({ duration: 10 });
    this.setData({ animationBar: this.__animationBar.export() });
  },

  animationAudioplayBlock(status) {
    status === 'playing' && this.__animationBlock.translateX(this.data.x).step();
    status === 'stop' && this.__animationBlock.translateX(0).step({ duration: 10 });
    this.setData({ animationBlock: this.__animationBlock.export() });
  },

  audioContext() {
    this.__innerAudioContext.autoplay = false;
    this.__innerAudioContext.src = this.data.existCard.audio;
    this.__innerAudioContext.onPlay(() => {
      console.log('开始播放');
      this.setData({ audioStatus: 'playing', audioStatusLabel: '播放' });
      this.animationAudioplayBar('playing');
      this.animationAudioplayBlock('playing');
    });
    this.__innerAudioContext.onPause(() => {
      console.log('暂停播放');
      this.setData({ audioStatus: 'pause' });
    });
    this.__innerAudioContext.onStop(() => {
      console.log('停止播放');
      this.setData({ audioStatus: 'stop', audioStatusLabel: '停止' });
      this.animationAudioplayBar('stop');
      this.animationAudioplayBlock('stop');
    });
    this.__innerAudioContext.onEnded(() => {
      console.log('播放结束');
      this.setData({ audioStatus: 'stop', audioStatusLabel: '停止' });
      this.animationAudioplayBar('stop');
      this.animationAudioplayBlock('stop');
    });
  },

  audioPlay() {
    console.log('will play');
    this.__innerAudioContext.play();
  },

  audioPause() {
    console.log('will pause');
    this.__innerAudioContext.pause();
  },

  audioStop() {
    this.__innerAudioContext.stop();
    this.animationAudioplayBar('stop');
    this.animationAudioplayBlock('stop');
  },

  getLiveScreen() {
    wx.getSystemInfo({
      success: res => {
        this.setData({ screenWidth: res.screenWidth, x: (res.screenWidth - 60) * 0.76 * 0.7 });
      },
    });
  },

  gotoList(e) {
    app.util.navigateTo('common/component/universal-card/pages/card-list');
  },

  // 本人名片开始
  // 获取名片详细信息
  getCardDetail(openid) {
    let that = this;
    let qr_path = 'common/component/universal-card/card-show';

    app.util.request({
      url: 'card/api/get_card_detail',
      data: { openid, qr_path },
      success: function (res) {
        if (Number(res.data.errno) === 0) {
          let existCard = res.data.data;
          that.setData({
            existCard,
          }, () => {
            that.audioContext();
            that.createAnimation(existCard.audioDuration);
            that.getCardRecommentGoodsList(openid);
            that.getMessageTip(openid)
          });
          // 用户还没有名片
          if (!existCard.id) {
            // app.util.navigateTo('common/component/universal-card/pages/card-edit', {}, true);
            // !that._privateData.isUnloaded && that.setData({
            //   isEmptyCard: true,
            // });
            app.util.request({
              url:'card/api/getSaleCardInfo',
              success: res => {
                if (Number(res.data.errno) === 0) {
                  //that.checkAuth();
                  const existCard = res.data.data;
                  console.log("=====existCard======",existCard)
                  existCard.images = (existCard.images || []);
                  that.setData({
                    existCard,
                    isMySelf: false,
                  }, () => {
                    that.audioContext();
                    that.createAnimation(existCard.audioDuration);
                    that.getCardRecommentGoodsList(existCard.openid);
                  });
                  wx.setStorageSync('masterInfo', existCard);  // 留言页面用到
                  // 获取针对该用户的访客信息
                  app.util.request({
                    url: 'card/api/get_member_record',
                    data: {
                      openid: existCard.openid,
                      op: '1',
                      page: '1',
                      pagesize: '10',
                      cardid: existCard.id || id,
                    },
                    success: function (res) {
                      if (Number(res.data.errno) === 0) {
                        const guests = res.data.data.list;
                        const guestsCount = Number(res.data.data.total);
                        that.setData({
                          guests: guests.slice(0, 5),
                          guestsCount,
                        });
                      }
                    },
                  });
                  if (_util.first_visit) {
                    that.setData({
                      showPopover: true,
                      showMyPopover: true,
                    })
                    setTimeout(() => {
                      that.setData({
                        showMyPopover: false,
                      })
                    }, 3000)

                    setTimeout(() => {
                      that.setData({
                        showPopover: false,
                        showWelcome: true,
                      })
                      _util.first_visit = false;
                    }, 10000)
                  }
                }
              }
            });
            return;
          }
          if (Number(existCard.ur_msg) > 0 && !app.isCheckedCardMsg) {
            wx.showModal({
              title: '提示',
              content: `你有${existCard.ur_msg}条未读消息`,
              success: function (res) {
                app.isCheckedCardMsg = true;
                if (res.confirm) {
                  that.gotoMsgList();
                } else if (res.cancel) {
                  // console.log('用户点击取消');
                }
              },
            });
          }
          wx.setStorageSync('masterInfo', existCard);  // 留言页面用到
          app.util.request({
            url: 'card/api/get_member_record',
            data: {
              openid,
              op: '1',
              page: '1',
              pagesize: '10',
              cardid: existCard.id,
            },
            success: function (res) {
              if (res.data.errno === 0) {
                const guests = res.data.data.list;
                const guestsCount = Number(res.data.data.total) || 0;
                that.setData({
                  guests: guests.slice(0, 5),
                  guestsCount,
                });
              }
            },
          });
          // 获取在线时间段
          app.util.request({
            url: 'card/api/get_service_time',
            data: {
              card_id: existCard.id,
            },
            success: res => {
              // 处理availablePeriods.day;
              let periods = res.data.data;
              let weekDay = { 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六' };
              periods.map(item => {
                if (item.day) item.day = item.day.split(',').map(i => { return '周' + (Number(i) === 0 ? '日' : weekDay[i]) }).join();
                return item;
              });
              that.setData({
                availablePeriods: periods,
              });
            },
          });
        }
      },
    });
  },

  // 留言提醒
  getMessageTip(openid){
    app.util.request({
      url:'card/record/getMessageTip',
      data:{
        openid,
      },
      success: res =>{
        console.log("======getMessageTip=====", res)
        if (res.data.errcode == 0){
          this.setData({
            isShowBadge: res.data.data? true : false,
          })
        }
      }
    })
  },

  // 前往编辑页面
  gotoEdit(e) {
    let url = e.currentTarget.dataset.type === 'edit'
      ? 'common/component/universal-card/pages/card-edit?goback=common/component/universal-card/card-show'
      : 'common/component/universal-card/pages/card-list';
    app.util.navigateTo(url);
  },

  callMe(e) {
    let phoneNumber = this.data.existCard.mobile;
    if (e.currentTarget.dataset.phone) phoneNumber = e.currentTarget.dataset.phone;

    const exp = app.util.phoneExp.mobile;
    if (phoneNumber && exp.test(phoneNumber)) {
      wx.makePhoneCall({
        phoneNumber,
      });
    } else if (phoneNumber && !exp.test(phoneNumber)) {
      wx.showToast({
        title: '无效的号码',
        icon: 'none',
      });
    } else {
      wx.showToast({
        title: '该用户没留下手机号码',
        icon: 'none',
      });
    }
  },

  showMyCode(e) {
    app.util.navigateTo(`common/component/universal-card/pages/msg-list?isPoster=1&openid=${this.data.openid}`);
  },

  closeMyCode(e) {
    this.setData({
      xcxCodeShow: false,
    });
  },

  // 查看访客列表
  checkGuests(e) {
    let { id: cardId, issale } = this.data.existCard;
    let url = 'common/component/universal-card/pages/guests-list?cardId=' + cardId + '&issale=' + issale;
    app.util.navigateTo(url);
  },

  getLastCard(openid) {
    if (openid) {
      app.util.request({
        url: 'card/api/get_record_last',
        data: {
          openid,
        },
        success: res => {
          if (res.data && res.data.errno === 0) {
            const { cardid, openid: cardOpenid } = res.data.data;
            if (openid === cardOpenid) return this.goToPreview();
            if (cardid && cardOpenid) {
              this.cardInfoInit(openid, cardid, cardOpenid);
              this.setData({ openid, self: openid === cardOpenid, id: cardid, fromOpenid: cardOpenid });
            } else {
              this.goToPreview();
            }
          }
        },
      });
    }
  },

  toggleCardList() {
    this.setData({
      showCardList: !this.data.showCardList,
    });
    this.getCardList();
  },

  getCardList() {
    if (this.data.loadingCardList) {
      return;
    }
    this.setData({ loadingCardList: true });
    app.util.request({
      url: 'card/api/sale_list',
      data: {
        m_openid: this.data.existCard.openid,
      },
      success: res => {
        if (res.data && res.data.errno === 0) {
          this.setData({
            cardList: res.data.data,
            loadingCardList: false,
          });
        }
      },
    });
  },

  onCardTapped(e) {
    const { item } = e.currentTarget.dataset;
    if (this.data.openid === item.openid) return this.goToPreview();
    this.setData({
      self: this.data.openid === item.openid,
      id: item.id,
      fromOpenid: item.openid,
      cardList: [],
      showCardList: false,
    });
    this.cardInfoInit(this.data.openid, item.id, item.openid);
  },

  // 获取历史访问名片
  getLastCards(openid){
    app.util.request({
      url:'card/record/myHistory',
      data:{
        openid,
        page: 1,
        pagesize:100
      },
      success: res =>{
        if (res.data.errcode == 0){
          this.setData({
            lastCardsList: res.data.data
          })
        }
      }
    })
  },

  // 打开历史访问弹框
  openLast(){
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid') || wx.getStorageSync('userInfo').openid;
    this.getLastCards(openid);
    this.setData({
      isShowLast: true
    });
  },

  // 关闭历史访问弹框
  closeLast(){
    this.setData({
      isShowLast: false
    })
  },

  goToLast(e){
    let { cardid, openid: to_openid } = e.currentTarget.dataset.item;
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid') || wx.getStorageSync('userInfo').openid;
    this.cardInfoInit(openid, cardid, to_openid);
    this.setData({
      isShowLast: false
    })
  },

  goToMyCard(){
    app.util.navigateTo('common/component/universal-card/card-preview')
  },

  // 获取推荐商品
  getCardRecommentGoodsList(from_openid){
    let module = app.siteInfo.module;
    let {isMySelf} = this.data;
    let params = {};
    params.from_openid = from_openid;
    if (module === 'ws_micro_shop') {
      params.store_id = app.ws_micro_shop_globalData.shopid || '';
    }
    params.from_openid = from_openid;
    app.util.request({
      url:'card/record/getCardRecommentGoodsList',
      data: params,
      success: res => {
        if(res.data.errno == 0){
          let recommendData = {
            isMySelf,
            goodsList: res.data.data.recommentGoods
          };
          this.setData({
            recommendData,
            homeUrl: res.data.data.homeUrl,
            shopHome: res.data.data.shopHome,
            website_title: res.data.data.website_title,
          })
        }
      }
    })
  },

  // 前往官网
  gotoWebsite(e){
    const module = app.siteInfo.appJson[app.tabbarindex].module;
    let { url } = e.currentTarget.dataset;
    this.setData({isRefresh: false})
    app.util.navigateTo(`/${module}/pages/web/web`, { url: url });
  },

  gotoBack(e){
    let { url } = e.currentTarget.dataset;
    app.util.navigateTo(url, {}, true);
  },

  getUserInfo(res){
    if(res.detail.userInfo){
      wx.setStorageSync('user_info',res.detail.userInfo)
      this.setData({
        isGetUserInfo: true
      })
    }
  },

  getUserMobile(res){
    if(res.detail.mobile){
      this.setData({
        isGetMobile: true
      })
    }
  },

  // 拨打电话
  callCustomer(res){
    this.setData({
      getUserInfoFn:'getUserInfo',
      getUserMobileFn:'getUserMobile'
    },()=>{
      if(!this.data.isGetUserInfo){
        this.setData({
          showGetUserInfo: true
        })
      } else if(!this.data.isGetMobile){
        this.setData({
          showBindMobile: true
        })
      } else {
        let { tel } = res.currentTarget.dataset;
        if (tel) {
          wx.makePhoneCall({
            phoneNumber: tel,
          });
        } else {
          wx.showModal({
            title: '提示',
            content: '暂无客户电话',
          });
        }
      }
    })
  },

  // 添加我微信
  addWechat(res) {
    this.setData({
      getUserInfoFn:'getUserInfo',
      getUserMobileFn:'getUserMobile'
    },()=>{
      if(!this.data.isGetUserInfo){
        this.setData({
          showGetUserInfo: true
        })
      } else if(!this.data.isGetMobile){
        this.setData({
          showBindMobile: true
        })
      } else {
        let wechatId = res.currentTarget.dataset.wechatid;
        wechatId && wx.setClipboardData({
          data: wechatId,
          success: () => {
            wx.showToast({
              title: '微信号已复制',
              icon: 'none'
            })
            this.collectAction('addWechat', true);
          },
          fail: () => {
            this.collectAction('addWechat', false);
          },
        });
      }
    })
  },

  // 添加邮箱
  addEmail(res) {
    this.setData({
      getUserInfoFn:'getUserInfo',
      getUserMobileFn:'getUserMobile'
    },()=>{
      if(!this.data.isGetUserInfo){
        this.setData({
          showGetUserInfo: true
        })
      } else if(!this.data.isGetMobile){
        this.setData({
          showBindMobile: true
        })
      } else {
        let email = res.currentTarget.dataset.email;
        email && wx.setClipboardData({
          data: email,
          success: () => {
            wx.showToast({
              title: '邮箱已经复制',
              icon: 'none'
            })
            this.collectAction('addEmail', true);
          },
          fail: () => {
            this.collectAction('addEmail', false);
          },
        });
      }
    })
  },

  addAddress(res){
    let address = res.currentTarget.dataset.address;
    address && wx.setClipboardData({
      data: address,
      success: () => {
        wx.showToast({
          title: '地址已经复制',
          icon:'none'
        })
        this.collectAction('addAddress', true);
      },
      fail: () => {
        this.collectAction('addAddress', false);
      },
    });
  },

  // 关闭欢迎弹框(看看再说)
  takeALook() {
    this.setData({
      getUserInfoFn: 'getLookUserInfo'
    },()=>{
      if(!this.data.isGetUserInfo){
        this.setData({
          showGetUserInfo: true
        }) 
      } else {
        this.setData({
          showWelcome: false
        })
      }
    })
  },

  // 看看再说:获取用户信息的回调
  getLookUserInfo(res){
    if(res.detail.userInfo){
      wx.setStorageSync('user_info',res.detail.userInfo)
      this.setData({
        isGetUserInfo: true,
      })
    }
    this.setData({
      showWelcome:false
    })
  },

  // 打开是否咨询回复弹框(聊一聊)
  chat(){
    this.setData({
      getUserInfoFn: 'getChatUserInfo'
    },()=>{
      if(!this.data.isGetUserInfo){
        this.setData({
          showGetUserInfo: true
        })
      } else {
        this.setData({
          showSubscription: true
        })
      }
    })
  },

  // 聊一聊:获取用户信息的回调
  getChatUserInfo(res){
    if(res.detail.userInfo){
      wx.setStorageSync('user_info',res.detail.userInfo)
      this.setData({
        isGetUserInfo: true
      })
    }
    this.setData({
      showSubscription: true
    })
  },

  // 拒绝咨询回复
  closeSubscription(){
    this.setData({
      showWelcome:false,
      showSubscription: false
    })
  },

  // 同意咨询回复
  agreeSubscription(){
    this.data.isWXWork?this.gotoMsg():this.requestSubscribeMessage()
  },

  //咨询
  consult(){
    this.setData({
      getUserInfoFn:'getConsultUserInfo',
      getUserMobileFn:'getConsultMobile',
      cancelAuthMobileFn: 'cancelAuthMobile'
    })
    if(!this.data.isGetUserInfo){ // 用户信息没授权
      this.setData({
        showGetUserInfo: true
      })
    } else if(!this.data.isGetMobile){ // 手机号没授权
      this.setData({
        showBindMobile: true
      })
    } else {
      if(this.data.firstConsult){
        this.setData({ showSubscription2: true })
      } else {
        this.data.isWXWork ? this.gotoMsg() : this.requestSubscribeMessage()
      }
    }
  },

  // 咨询:获取用户信息的回调
  getConsultUserInfo(res){
    if(res.detail.userInfo){
      wx.setStorageSync('user_info',res.detail.userInfo)
      this.setData({
        isGetUserInfo: true
      })
    }
    if(!this.data.isGetMobile){ // 手机号没授权
      this.setData({
        showBindMobile: true
      })
    } else {
      this.setData({ showSubscription2: true })
    }
  },

  // 咨询:获取手机号的回调
  getConsultMobile(res){
    if(res.detail.mobile){
      this.setData({
        isGetMobile: true,
        guestMobile: res.detail.mobile,
        showSubscription2: true
      })
    } 
  },

  // 咨询: 拒绝手机号回调
  cancelAuthMobile(){
    this.setData({ 
      showSubscription2: true,
      cancelAuthMobileFn: ''
    })
  },

  // 关闭
  closeMobile(){
    this.setData({
      showSubscription2:false,
      firstConsult: false
    })
  },

  agreeMobile(){
    this.setData({
      showSubscription2: false,
      firstConsult: false
    })
    this.data.isWXWork ? this.gotoMsg() : this.requestSubscribeMessage()
  },

  requestSubscribeMessage(){
    _util.requestSubscribeMessage().then(res =>{
      this.setData({
        showWelcome: false,
        showSubscription: false
      },()=>{this.gotoMsg()})
    }) .catch(err =>{
      this.setData({
        showWelcome: false,
        showSubscription: false
      })
    })
  },

  // 判断用户手机号
  checkUserTelephone(openid) {
    const that = this;
    // let user_info = wx.getStorageSync("user_info") || {}
    app.util.request({
      url: 'card/api/is_up_user',
      data: {
        openid,
        type: 'is_phone',
      },
      success: function (res) {
        console.log("======is_up_user========",res);
        if (Number(res.data.data) === 0) {
          that.setData({
            isGetMobile: false,
          });
        } else if (Number(res.data.data) === 1) {
          that.setData({
            isGetMobile: true,
            guestMobile: res.data.uinfo.phone
          });
        }
      },
    });
  },

  // 判断用户授权
  checkAuth() {
    getUserInfo()
      .then((res) => {
        this.setData({isGetUserInfo:true})
        console.log("=======isGetUserInfo then======",this.data.isGetMobile)
      })
      .catch(res => {
        this.setData({isGetUserInfo:false})
        console.log("=======isGetUserInfo catch======",this.data.isGetMobile)
      });
    
  },
});
